<template>
  <div class="attraction-form-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <h2>景点信息管理</h2>
          <p>填写完整的景点信息</p>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="attraction-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="景点名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入景点名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="景点分类" prop="category">
                <el-select v-model="formData.category" placeholder="请选择景点分类" style="width: 100%">
                  <el-option label="历史文化" value="历史文化" />
                  <el-option label="自然风光" value="自然风光" />
                  <el-option label="主题公园" value="主题公园" />
                  <el-option label="宗教场所" value="宗教场所" />
                  <el-option label="现代建筑" value="现代建筑" />
                  <el-option label="休闲娱乐" value="休闲娱乐" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="门票价格" prop="price">
                <el-input-number v-model="formData.price" :min="0" :max="9999" :precision="0" style="width: 100%" placeholder="0表示免费" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="详细地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入详细地址" clearable />
          </el-form-item>
        </div>

        <!-- 营业信息 -->
        <div class="form-section">
          <h3 class="section-title">营业信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开放时间" prop="openHours">
                <el-input v-model="formData.openHours" placeholder="例如：08:30-17:00" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日均访客" prop="visitors">
                <el-input-number v-model="formData.visitors" :min="0" :max="999999" :precision="0" style="width: 100%" placeholder="日均访客数量" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="景点评分" prop="rating">
            <el-rate v-model="formData.rating" :max="5" :precision="0.1" show-score text-color="#ff9900" score-template="{value} 分" />
          </el-form-item>
        </div>

        <!-- 标签管理 -->
        <div class="form-section">
          <h3 class="section-title">标签管理</h3>
          <el-form-item label="景点标签" prop="tags">
            <div class="tags-container">
              <el-tag v-for="tag in formData.tags" :key="tag" closable @close="removeTag(tag)" class="tag-item">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" class="tag-input" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
              <el-button v-else class="button-new-tag" size="small" @click="showInput"> + 添加标签 </el-button>
            </div>
            <div class="preset-tags">
              <span class="preset-label">常用标签：</span>
              <el-tag v-for="tag in presetTags" :key="tag" class="preset-tag" @click="addPresetTag(tag)" :class="{ disabled: formData.tags.includes(tag) }">
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>
        </div>

        <!-- 描述信息 -->
        <div class="form-section">
          <h3 class="section-title">描述信息</h3>
          <el-form-item label="景点描述" prop="description">
            <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入景点的详细描述，包括特色、历史背景等" maxlength="500" show-word-limit />
          </el-form-item>
        </div>

        <!-- 图片管理 -->
        <div class="form-section">
          <h3 class="section-title">图片管理</h3>
          <el-form-item label="景点图片">
            <div class="image-upload-container">
              <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload" multiple>
                <el-icon><Plus /></el-icon>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </div>
            <div class="upload-tip">
              <el-text size="small" type="info"> 支持 jpg、png、gif 格式，单张图片不超过 2MB，最多上传 5 张 </el-text>
            </div>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">发布景点</el-button>
          <el-button @click="resetForm">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/apis/scene'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'

// 响应式数据
const formRef = ref<FormInstance>()
const inputRef = ref()
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const inputVisible = ref(false)
const inputValue = ref('')
const fileList = ref<UploadUserFile[]>([])

// 表单数据
const formData = reactive({
  name: '东川大菜园',
  province: '云南省',
  city: '昆明市',
  address: '东川区景山前街4号',
  description: '明清皇家宫殿，世界文化遗产。',
  category: '历史文化',
  openHours: '08:30-17:00',
  price: 0,
  rating: 4.8,
  tags: ['历史文化'],
  visitors: 8000,
  imageUrls: ['https://picsum.photos/300/200?random=1']
})

// 预设标签
const presetTags = ref(['古建筑', '博物馆', '自然风光', '亲子游', '情侣约会', '摄影胜地', '历史遗迹', '宗教文化', '民俗风情', '美食天堂', '购物天堂', '夜景'])

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '景点名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [{ required: true, message: '请选择景点分类', trigger: 'change' }],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入景点描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  openHours: [{ required: true, message: '请输入开放时间', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入门票价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ],
  visitors: [
    { required: true, message: '请输入日均访客数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '访客数量不能小于0', trigger: 'blur' }
  ]
}

const removeTag = (tag: string) => {
  const index = formData.tags.indexOf(tag)
  if (index > -1) {
    formData.tags.splice(index, 1)
  }
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !formData.tags.includes(inputValue.value)) {
    formData.tags.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const addPresetTag = (tag: string) => {
  if (!formData.tags.includes(tag)) {
    formData.tags.push(tag)
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      // 构建提交数据
      const submitData = {
        ...formData,
        tagsJson: JSON.stringify(formData.tags),
        imageUrls: JSON.stringify(formData.imageUrls)
      }
      // return console.log('提交数据:', submitData)
      http
        .create(submitData)
        .then((response) => {
          let { code, message } = response.data
          if (code !== 200) {
            throw new Error(message || '提交失败')
          }
          ElMessage.success('景点信息提交成功!')
          formRef.value?.resetFields()
          formData.tags = []
          fileList.value = []
        })
        .catch((error) => {
          console.error('提交失败:', error)
          ElMessage.error('提交失败，请稍后重试!')
        })
    } else {
      ElMessage.error('请检查表单填写是否完整!')
    }
  })
}

const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    formData.tags = []
    fileList.value = []
    ElMessage.success('表单已重置')
  })
}
</script>

<style scoped>
.attraction-form-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.attraction-form {
  padding: 20px 0;
}

.form-section {
  margin-bottom: 32px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 4px;
}

.tag-input {
  width: 120px;
}

.button-new-tag {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  font-size: 12px;
}

.preset-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 4px;
}

.preset-label {
  color: #606266;
  font-size: 12px;
  white-space: nowrap;
}

.preset-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.preset-tag:hover:not(.disabled) {
  background: #409eff;
  color: white;
}

.preset-tag.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.image-upload-container {
  margin-bottom: 8px;
}

.upload-tip {
  margin-top: 8px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .attraction-form-container {
    padding: 10px;
  }

  .form-section {
    padding: 16px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}
</style>
